import random
import pygame
from plane_sprites import *

class PlanGame(object):
    #游戏初始化
    def __init__(self):
        # 创建游戏主屏幕
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)

        self.start_game_botton = False
        self.start_game_text = False
        self.gameover_botton = False
        self.stop_img = False
        self.continue_img = False
    def home(self):
        # 绘制游戏开始界面

        # 创建背景精灵和精灵组
        bg = Background()
        bg_group = pygame.sprite.Group(bg)

        # 更新背景精灵组
        bg_group.draw(self.screen)

        self.clock = pygame.time.Clock()
        pygame.font.init()

        # 开始游戏按钮
        self.start_game_botton = GameSprite("./images/resume_pressed.png")
        self.start_game_botton.rect.center = (SCREEN_RECT.centerx, SCREEN_RECT.centery-30)

        img_group = pygame.sprite.Group(self.start_game_botton)

        # 更新背景精灵组
        img_group.draw(self.screen)

        text_surface = pygame.font.SysFont('SimHei', 40).render('飞机大战游戏', True, '#363535')
        text_rect = text_surface.get_rect()
        text_rect.center = (SCREEN_RECT.centerx, SCREEN_RECT.top + 200)
        self.screen.blit(text_surface, text_rect)


        text_surface2 = pygame.font.SysFont('SimHei', 25).render('开始游戏', True, '#626060')
        self.start_game_text = text_surface2.get_rect()
        self.start_game_text.center = (SCREEN_RECT.centerx, self.start_game_botton.rect.centery+60)
        self.screen.blit(text_surface2, self.start_game_text)

        top_score = (ScoreClass()).load_score()
        text_surface3 = pygame.font.SysFont('SimHei', 15).render('最高分数 %d' % top_score, True, '#626060')
        text_rect3 = text_surface3.get_rect()
        text_rect3.center = (SCREEN_RECT.centerx, self.start_game_text.centery + 40)
        self.screen.blit(text_surface3, text_rect3)


        while True:
            self.clock.tick(FRAME_PER_SEC)
            self.__event_handler_globals()  # 游戏全局监听
            # 更新屏幕显示
            pygame.display.flip()
        pygame.display.update()#更新屏幕显示
        # pygame.quit()
        # exit()


    def __create_sprites(self):
        # #创建背景精灵和精灵组
        bg1 = Background()
        bg2 = Background(is_alt=True)

        self.back_group = pygame.sprite.Group(bg1,bg2)

        # 创建敌机精灵组
        self.enemy_group = pygame.sprite.Group()
        self.enemy_group_nokill = pygame.sprite.Group()

        #创建英雄的精灵和精灵组
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)

        #创建文字精灵和精灵组
        self.test_group = pygame.sprite.Group()

        # 暂停游戏按钮
        self.stop_img = GameSprite("./images/pause_pressed.png")
        self.stop_img.act = 'stop'
        # self.stop_img.rect.centerx = SCREEN_RECT.centerx
        # self.stop_img.rect.centery = SCREEN_RECT.centery - self.stop_img.rect.width - 30

        self.stop_img.rect.right = SCREEN_RECT.right - 40
        self.stop_img.rect.top = SCREEN_RECT.top + 40
        self.img_group = pygame.sprite.Group(self.stop_img)

    # 监听
    #启动游戏
    def start_game(self):
        print("游戏开始....")

        self.game_time = 0;  # 游戏时间，利用创建敌机定时器，1秒+1
        self.game_score = 0;  # 游戏分数，销毁一架敌机+1
        self.game_status = True;  # 游戏暂停

        self.start_game_text = False

        self.clock = pygame.time.Clock()
        self.__create_sprites()

        #定时器----定时创建敌机 1s(毫秒)
        pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)

        #定时器----英雄定时发射子弹 0.5s(毫秒)
        pygame.time.set_timer(HERO_FIRE_EVENT,500)


        while True:
            self.clock.tick(FRAME_PER_SEC)
            if self.game_status:
                self.__event_handler()#游戏监听
                self.__check_collide()#碰撞检测
                self.__update_sprites()  # 更新精灵组

                # pygame.display.flip()#更新屏幕显示(文字)
            else:
                self.stop_game()

            # self.__update_sprites()  # 更新精灵组
            self.__event_handler_globals()

            pygame.display.update()  # 更新屏幕显示
    # 游戏控制监听
    def __event_handler(self):
        # 事件监听,控制飞机左右、退出
        for event in pygame.event.get():
            #创建敌机
            if event.type == CREATE_ENEMY_EVENT:
                if self.hero and self.hero.is_survive:
                    self.game_time += 1

                #敌机速度，10分速度+1
                speed = int(self.game_score/10) + 1

                # 创建敌机精灵
                enemy = Enemy(speed=speed)
                #将敌机精灵添加到敌机精灵组
                self.enemy_group.add(enemy)

                #超过20分后，5秒出一个导弹
                if self.game_score >= 20 and self.game_time%5 == 0:
                    enemy = Enemy(SUPPLY_IMG,speed+1)
                    self.enemy_group_nokill.add(enemy)

                # 超过30分后，3秒出一个鱼雷
                if self.game_score >= 30 and self.game_time%3 == 0:
                    enemy = Enemy(BOMB_IMG, speed+2)
                    self.enemy_group_nokill.add(enemy)

            #英雄发射子弹
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()
        #英雄移动控制
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_UP]:
            # 上
            self.hero.speed_y = -2
        elif keys_pressed[pygame.K_DOWN]:
            # 下
            self.hero.speed_y = 2
        elif keys_pressed[pygame.K_LEFT]:
            #左
            self.hero.speed = -2
        elif keys_pressed[pygame.K_RIGHT]:
            #右
            self.hero.speed = 2
        else:
            self.hero.speed = 0
            self.hero.speed_y = 0
    #游戏全局监听
    def __event_handler_globals(self):
        # 事件监听,控制飞机左右、退出
        for event in pygame.event.get():
            # print("游戏监听~~%d------111" % event.type)
            # 退出
            if event.type == pygame.QUIT:
                self.__exit_game()
            # 检查鼠标点击事件
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # #点击开始游戏按钮
                # if self.start_game_botton and self.start_game_botton.rect.collidepoint(event.pos):
                if self.start_game_botton and self.start_game_botton.rect.collidepoint(pygame.mouse.get_pos()):
                    if pygame.mouse.get_pressed()[0]:
                        print("开始游戏1111~~")
                        self.start_game()
                # elif self.start_game_text and self.start_game_text.collidepoint(event.pos):
                elif self.start_game_text and self.start_game_text.collidepoint(pygame.mouse.get_pos()):
                    if pygame.mouse.get_pressed()[0]:
                        print("开始游戏2222~~")
                        self.start_game()
                #点击结束游戏按钮
                # elif self.gameover_botton and self.gameover_botton.rect.collidepoint(event.pos):
                elif self.gameover_botton and self.gameover_botton.rect.collidepoint(pygame.mouse.get_pos()):
                    if pygame.mouse.get_pressed()[0]:
                        self.home()
                #点击暂停游戏按钮
                # elif self.stop_img and self.stop_img.rect.collidepoint(event.pos):
                elif self.stop_img and self.stop_img.rect.collidepoint(pygame.mouse.get_pos()):
                    if pygame.mouse.get_pressed()[0]:
                        # print(self.stop_img.act)
                        print("暂停游戏~~")
                        self.game_status = False
                #点击继续游戏按钮
                # elif self.continue_img and self.continue_img.rect.collidepoint(event.pos):
                elif self.continue_img and self.continue_img.rect.collidepoint(pygame.mouse.get_pos()):
                    if pygame.mouse.get_pressed()[0]:
                        # print(self.continue_img.act)
                        print("继续游戏~~")
                        self.game_status = True
                else:
                    pass

    #碰撞检测
    def __check_collide(self):
        #子弹摧毁敌机,分数+1
        enemys1 = pygame.sprite.groupcollide(self.enemy_group,self.hero.bullet , False, True)
        # if pygame.sprite.groupcollide(self.hero.bullet,self.enemy_group,True,False):
        if enemys1:
            if self.hero.is_survive:
                self.game_score += 1
            for e in enemys1:
                e.die_animation()

        #敌机撞毁英雄
        enemys2 = pygame.sprite.spritecollide(self.hero,self.enemy_group,True)
        enemys3 = pygame.sprite.spritecollide(self.hero,self.enemy_group_nokill,True)

        if len(enemys2) > 0 or len(enemys3) > 0:
            #让英雄牺牲
            self.hero.die_animation()
            #结束游戏
            # self.__game_over()

    #更新/绘制精灵组
    def __update_sprites(self):

        #检测英雄是否存活
        if self.hero.is_game_over == False:
            #更新背景精灵组
            self.back_group.update()
            self.back_group.draw(self.screen)

            #更新敌机精灵组
            self.enemy_group.update()
            self.enemy_group.draw(self.screen)

            self.enemy_group_nokill.update()
            self.enemy_group_nokill.draw(self.screen)

            #更新英雄精灵组
            self.hero_group.update()
            self.hero_group.draw(self.screen)

            #更新子弹精灵组
            self.hero.bullet.update()
            self.hero.bullet.draw(self.screen)


            #更新文字精灵组
            self.test_group.empty()
            test = TextSprite('游戏时间 %d' % self.game_time,1)
            test2 = TextSprite('当前分数 %d' % self.game_score)

            test.rect.right = SCREEN_RECT.right - 20
            test.rect.bottom = SCREEN_RECT.bottom - 30

            test2.rect.centerx = SCREEN_RECT.centerx
            test2.rect.centery = SCREEN_RECT.centery


            self.test_group.add(test)
            self.test_group.add(test2)
            # self.test_group.update()
            self.test_group.draw(self.screen)
            # self.screen.blit(self.text,self.text_rect)

            self.img_group.draw(self.screen)
        else:
            self.__game_over()
    #游戏结束页面
    def __game_over(self):
        # 绘制游戏结束界面
        # mask_surface = pygame.Surface((SCREEN_RECT.width, SCREEN_RECT.height), pygame.SRCALPHA)
        #
        # mask_surface.fill((128, 128, 128))  # 用黑色填充屏幕
        # self.screen.blit(mask_surface,(0,0))

        #保存游戏分数
        (ScoreClass()).save_score(self.game_score)

        # 创建背景精灵和精灵组
        bg = Background()
        bg_group = pygame.sprite.Group(bg)

        # 更新背景精灵组
        bg_group.draw(self.screen)

        #重新开始按钮
        self.start_game_botton = GameSprite("./images/again.png")
        self.start_game_botton.rect.centerx = SCREEN_RECT.centerx
        self.start_game_botton.rect.centery = SCREEN_RECT.centery-30

        # 结束游戏按钮
        self.gameover_botton = GameSprite("./images/gameover.png")
        self.gameover_botton.rect.centerx = SCREEN_RECT.centerx
        self.gameover_botton.rect.centery = SCREEN_RECT.centery+30

        img_group = pygame.sprite.Group(self.start_game_botton,self.gameover_botton)
        img_group.draw(self.screen)

        text_surface = pygame.font.SysFont('SimHei', 30).render('游戏结束~~', True, '#e91616')
        text_rect = text_surface.get_rect()
        text_rect.center = (SCREEN_RECT.centerx, SCREEN_RECT.top + 160)
        self.screen.blit(text_surface, text_rect)

        text_surface2 = pygame.font.SysFont('SimHei', 30).render('当前分数 %d' % self.game_score, True, (255, 255, 255))
        text_rect2 = text_surface2.get_rect()
        text_rect2.center = (SCREEN_RECT.centerx, SCREEN_RECT.centery - 100)
        self.screen.blit(text_surface2, text_rect2)

        # 更新屏幕显示
        pygame.display.flip()

    # 暂停游戏
    def stop_game(self):
        # 创建背景精灵和精灵组
        bg = Background()
        bg_group = pygame.sprite.Group(bg)

        # 更新背景精灵组
        bg_group.draw(self.screen)

        # 重新开始按钮
        self.start_game_botton = GameSprite("./images/again.png")
        self.start_game_botton.rect.centerx = SCREEN_RECT.centerx
        self.start_game_botton.rect.centery = SCREEN_RECT.centery - 30

        # 结束游戏按钮
        self.gameover_botton = GameSprite("./images/gameover.png")
        self.gameover_botton.rect.centerx = SCREEN_RECT.centerx
        self.gameover_botton.rect.centery = SCREEN_RECT.centery + 30

        # 继续游戏按钮
        self.continue_img = GameSprite("./images/resume_pressed.png")
        self.continue_img.act = 'continue'
        self.continue_img.rect.centerx = SCREEN_RECT.centerx
        self.continue_img.rect.centery = self.start_game_botton.rect.centery - 70

        img_group = pygame.sprite.Group(self.start_game_botton, self.gameover_botton,self.continue_img)

        # 更新背景精灵组
        img_group.draw(self.screen)

        # 更新屏幕显示
        pygame.display.flip()


    #退出游戏
    @staticmethod
    def __exit_game():
        pygame.quit()
        exit()
if __name__ == '__main__':
    #创建游戏对象
    game = PlanGame()

    #启动游戏
    game.home()
    # game.start_game()